<?php declare(strict_types=1);

namespace think\msg;

use app\ExceptionHandle;
use think\msg\constant\MsgTypeConstant;
use think\msg\facade\Msg;
use think\msg\msg\RichTextMsg;
use think\msg\msg\TextMsg;
use Throwable;

class ExceptionReportHandle extends ExceptionHandle
{
    /**
     * @param Throwable $e
     * @return void
     * @throws MsgException
     */
    public function report(Throwable $e): void
    {
        $moduleName = $this->app->http->getName() ?: 'backgroundTask';
        $requestId = $this->app->request->requestId ?? '未生成 requestId';
        $config = $this->app->config->get('msg');
        $enable = $config['exception_report']['enable'];
        $appName = $this->app->config->get('app.app_name');
        $logWebUrl = $config['exception_report']['log_web_url'];
        $traceLength = $config['exception_report']['trace_length'];
        parent::report($e);
        // 接管异常记录
        if ($this->isIgnoreReport($e) || $this->app->isDebug() || !$enable) {
            // 调试模式或忽略的报错，不发送模板消息
            return;
        }
        $msgType = $config['exception_report']['msg_type'];
        /** @var \think\msg\msg\Msg $msg */
        if ($msgType === MsgTypeConstant::TEXT) {
            $msg = TextMsg::build()->setContent($e->getMessage());
        } elseif (MsgTypeConstant::RICH_TEXT === $msgType) {
            $title = sprintf('%s - %s - 异常通知', $appName, $moduleName);
            $msg = RichTextMsg::build()->setTitle($title)->setContent([
                [
                    [
                        'tag' => 'text',
                        'text' => $e->getMessage(),
                    ],
                ],
                [
                    [
                        'tag' => 'text',
                        'text' => sprintf('RequestId：%s', $requestId),
                    ],
                ],
                [
                    [
                        'tag' => 'text',
                        'text' => sprintf('位置：%s，行号：%d', $e->getFile(), $e->getLine()),
                    ],
                ],
                [
                    [
                        'tag' => 'text',
                        'text' => '异常调用栈：',
                    ],
                ],
                [
                    [
                        'tag' => 'a',
                        'text' => mb_substr($e->getTraceAsString(), 0, $traceLength, 'utf-8'),
                        'url' => $logWebUrl,
                    ],
                ]
            ]);
        }

        // 异步推送消息
        try {
            Msg::asyncSend($msg);
            // Msg::send($msg);
        } catch (Throwable $e) {
            // 忽略异常
        }
    }
}